// 获取应用实例
const app = getApp();
const departmentArr = ['综合办', '交接处', '工程部', '已完结'];
Page({
    data: {
        productInfo: [],
        select: true,
        name: '', // 工单人姓名 
        tel: '', // 电话
        money: '', // 装修数量
        reviewTel: '', // 复核信息
        typeName: '',
        affiliatedName: '',
        explains: '', // 说明
        isDelivery: 0,
        isPlacement: 0,
        picture: '', // 照片最多三张多个逗号隔开
        type: '',
        id: '',
        days: '0',
        list: [],
        sign1: '0',
        sign2: '0',
        sign3: '0',
        isOpen: false,
        detailShow: false,
        detailItem: {},
        evaluateData: [],
        isOpen1: false,
        status: '综合办',
        collectionList: [],
        changeList: [],
        allMoneyData: {},
        total: 0,
        placementTime: '',
        placementUserName: '',
        deliveryTime: '',
        deliveryUserName: '',
        fan: '', // 开扇数量
        door: '', // 开门数量
        tube: '', // 方管数量
        inversion: '', // 内倒数量
        transfer: '', // 转角数量
        window: '', // 纱窗数量
        attachment: [],
        packName: '',
        brandName: '',
        materialName: '',
        thicknessName: '',
        openName: '',
        admin: 0,
        subAdmin: 0,
        isMe: false,
        share: false,
        sale: 0,
        dpId: 0,
        agreementShow: false,
        content: '',
        title: ''
    },
    onLoad(option) {
        this.setData({
            id: option.id,
            admin: wx.getStorageSync('admin'),
            subAdmin: wx.getStorageSync('subAdmin'),
            share: option?.share,
            sale: option?.sale
        });
        
        this.getDepartment(option.id);
        this.getChangeData();
        this.getReceiptsData();
        this.getAllMoney();
        this.getPrivery();
        if(option?.sale == 1) wx.hideShareMenu();
    },
    onShow() {
        this.getEvaluateList();
    },
    //刷新
    onPullDownRefresh() {

    },
    // 获取财务工单详情
    getDepartment(id) {
        wx.request({
            url: `${app.globalData.baseUrl}/api/finance/selById`,
            method: "GET",
            header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
            },
            data: {
                id: id,
            },
            success: (res) => {
                if (res.data.code == 0) {
                    if (res.data.data.length != 0) {
                        res.data.data.list.forEach((item, index) => {
                            item.index = res.data.data.list?.length - index;
                        });
                        if (res.data.data.userId == wx.getStorageSync('userId')) this.setData({})
                        this.setData({
                            isMe: res.data.data.userId == wx.getStorageSync('userId') ? true : false,
                            name: res.data.data.name,
                            tel: res.data.data.tel,
                            money: res.data.data.money,
                            reviewTel: res.data.data.reviewTel,
                            affiliatedName: res.data.data.affiliatedName,
                            attachment: res.data.data.attachment ? res.data.data.attachment.split(',') : [],
                            typeName: res.data.data.typeName,
                            type: res.data.data.type,
                            explains: res.data.data.explains,
                            isDelivery: res.data.data.isDelivery,
                            isPlacement: res.data.data.isPlacement,
                            picture: res.data.data.picture && res.data.data.picture.split(','),
                            productInfo: res.data.data.picture && res.data.data.picture.split(','),
                            list: res.data.data.list,
                            days: res.data.data.days,
                            status: departmentArr[res.data.data.status],
                            dpId: res.data.data.status,
                            sign1: res.data.data.sign1,
                            sign2: res.data.data.sign2,
                            sign3: res.data.data.sign3,
                            total: res.data.data.total,
                            placementTime: res.data.data.placementTime,
                            placementUserName: res.data.data.placementUserName,
                            deliveryTime: res.data.data.deliveryTime,
                            deliveryUserName: res.data.data.deliveryUserName,
                            fan: res.data.data.fan, // 开扇数量
                            door: res.data.data.door, // 开门数量
                            tube: res.data.data.tube, // 方管数量
                            inversion: res.data.data.inversion, // 内倒数量
                            transfer: res.data.data.transfer, // 转角数量
                            window: res.data.data.window, // 纱窗数量
                            packName: res.data.data.packName,
                            brandName: res.data.data.brandName,
                            materialName: res.data.data.materialName,
                            thicknessName: res.data.data.thicknessName,
                            openName: res.data.data.openName,
                        })
                    } else {
                        wx.showToast({
                            title: res.data.msg || '报错啦！',
                            icon: 'error',
                            duration: 2000
                        })
                    }
                }
            }
        })
    },
    //预览图片，放大预览
    preview(e) {
        let currentUrl = this.data.productInfo;
        let index = e.currentTarget.dataset.index;
        wx.previewImage({
            current: currentUrl[index], // 当前显示图片的http链接
            urls: this.data.productInfo // 需要预览的图片http链接列表
        })
    },

    extractNumbersFromString(str) {
        let numbers = [];
        if (str.indexOf('】') > -1) {
            const arr = str.split('】');
            if (arr.length > 1) {
                numbers = arr[arr.length - 1].match(/\d+/g);
            }
        } else if (str.indexOf(']') > -1) {
            const arr = str.split(']');
            if (arr.length > 1) {
                numbers = arr[arr.length - 1].match(/\d+/g);
            }
        } else {
            numbers = str.match(/\d+/g);
        }
        return numbers;
    },
    tell() {
        const arr = this.extractNumbersFromString(this.data.tel);
        if (arr && arr.length > 0) {
            wx.makePhoneCall({
                phoneNumber: arr[arr.length - 1],
                success() {
                },
            })
        }
    },
    tellcover() {
        const arr = this.extractNumbersFromString(this.data.reviewTel);
        if (arr && arr.length > 0) {
            wx.makePhoneCall({
                phoneNumber: arr[arr.length - 1],
                success() {
                },
            })
        }
    },

    panel() {
        this.setData({
            isOpen: !this.data.isOpen
        })
    },

    viewDetail(e) {
        let detailItem = e.currentTarget.dataset.viewitem;
        detailItem.picture = detailItem.picture ? detailItem.picture.split(',') : [];
        this.setData({ detailShow: true, detailItem });
    },

    detialHide() {
        this.setData({ detailShow: false });
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: `工单详情 （发起距今${this.data.days}天）`,
            path: `/pages/financialDetails/index?id=${this.data.id}&share=true`
        }
    },

    evaluateOpen() {
        this.setData({ isOpen1: !this.data.isOpen1 });
    },

    preview_4(e) {
        const currentUrl = this.data.evaluateData;
        const index = e.currentTarget.dataset.index;
        const idex = e.currentTarget.dataset.idex;
        wx.previewImage({
            current: currentUrl[index].picture[idex], // 当前显示图片的http链接
            urls: [...currentUrl[index].picture] // 需要预览的图片http链接列表
        })
    },

    getEvaluateList() {
        wx.request({
            url: `${app.globalData.baseUrl}/api/notice/selCommentList?financeId=${this.data.id}`,
            method: "GET",
            header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
            },
            success: (res) => {
                if (res.data.code == 0) {
                    if (res.data.rows.length != 0) {
                        res.data.rows?.forEach((item, index) => {
                            item.picture = item.picture ? item.picture.split(',') : [];
                            item.index = res.data.rows.length - index;
                        })
                        this.setData({
                            evaluateData: res.data.rows
                        })
                    }
                } else {
                    if (this.data.workId) {
                        wx.showToast({
                            title: res.data.msg || '出错啦！',
                            icon: 'error',
                            duration: 2000
                        })
                    }
                }
            }
        })
    },

    download(e) {
      const that = this;
      wx.getSystemInfo({
        success: function(result) {
          if (result.platform === 'ios' || result.platform === 'android') {
            that.saveMobile(e.currentTarget.dataset.url);
          } else if (result.platform === 'windows' || result.platform === 'mac') {
            that.savePc(e.currentTarget.dataset.url);
          }
        }
      });
    },

    savePc(url) {
      wx.request({
        url: url,
        responseType: 'arraybuffer', // 设置响应类型为arraybuffer以接收二进制数据
        success: (res) => {
          // 获取文件名
          const fileName = url.split('/').pop();
       
          // 写入文件
          wx.getFileSystemManager().writeFile({
            filePath: wx.env.USER_DATA_PATH + '/' + fileName, // 指定要写入的文件路径
            data: res.data, // 文件内容
            encoding: 'binary', // 指定文件编码
            success: (writeRes) => {
              console.log('文件保存成功', writeRes);
              // 这里可以调用wx.saveFileToDisk将文件保存到用户电脑
              wx.saveFileToDisk({
                filePath: wx.env.USER_DATA_PATH + '/' + fileName,
                success: (saveRes) => {
                  console.log('文件保存到电脑成功', saveRes);
                },
                fail: (error) => {
                  console.error('文件保存到电脑失败', error);
                }
              });
            },
            fail: (error) => {
              console.error('文件保存失败', error);
            }
          });
        },
        fail: (error) => {
          console.error('文件下载失败', error);
        }
      });
    },
  
    saveMobile(url) {
      console.log(url, 'mobile')
      wx.downloadFile({
        url,
        success(res) {
          if (res.statusCode === 200) {
            console.log(res.tempFilePath)
            wx.openDocument({
              filePath: res.tempFilePath,
              showMenu: true
            });
          }
        }
      })
    },

    copyText(e) {
      wx.setClipboardData({
        data: e.currentTarget.dataset.url,
        success: function (res) {
          wx.showToast({
            title: '复制成功',
          });
        }
      });
    },

    // TOO 评价页面
    toEvaluate() {
        wx.navigateTo({
            url: `/pages/evaluate/index?id=` + this.data.id
        })
    },

    preview_5(e) {
        const currentUrl = this.data.detailItem.picture;
        const idex = e.currentTarget.dataset.idex;
        wx.previewImage({
            current: currentUrl[idex], // 当前显示图片的http链接
            urls: [...currentUrl] // 需要预览的图片http链接列表
        })
    },

    getChangeData(val) {
        wx.request({
            url: `${app.globalData.baseUrl}/api/classify/selChangeList?financeId=${this.data.id}`,
            method: "GET",
            header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
            },
            success: (res) => {
                if (res.data.code == 0) {
                    res.data.rows.forEach((item, index) => {
                        item.index = res.data.rows?.length - index;
                    });
                    this.setData({ changeList: res.data.rows });
                    if (val) this.getAllMoney();
                }
            }
        })
    },
    getReceiptsData(val) {
        wx.request({
            url: `${app.globalData.baseUrl}/api/classify/selCollectionList?financeId=${this.data.id}`,
            method: "GET",
            header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
            },
            success: (res) => {
                if (res.data.code == 0) {
                    res.data.rows.forEach((item, index) => {
                        item.index = res.data.rows?.length - index;
                    });
                    this.setData({ collectionList: res.data.rows });
                    if (val) this.getAllMoney();
                } else {
                    wx.showToast({
                        title: '系统异常',
                    });
                }
            },
            fail: () => {
                wx.showToast({
                    title: '系统异常',
                });
            }
        })
    },

    getAllMoney() {
        wx.request({
            url: `${app.globalData.baseUrl}/api/classify/selFinanceTotal?financeId=${this.data.id}`,
            method: "GET",
            header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
            },
            success: (res) => {
                if (res.data.code == 0) {
                    const obj = res.data.data;
                    obj.balanceTotal = parseFloat(res.data.data.changeTotal) - parseFloat(res.data.data.collectionTotal);
                    this.setData({ allMoneyData: obj });
                } else {
                    wx.showToast({
                        title: '系统异常',
                    });
                }
            },
            fail: () => {
                wx.showToast({
                    title: '系统异常',
                });
            }
        })
    },

    agreement() {
      this.setData({ agreementShow: true });
    },
  
    closeModal() {
      this.setData({ agreementShow: false });
    },

    getPrivery() {
      wx.request({
        url: `${app.globalData.baseUrl}/api/memo/sekByRuleId?id=2`,
        method: "GET",
        header: {
          'token': wx.getStorageSync('token'),
          "Content-Type": "application/json"
        },
        success: (res) => {
          if (res.data.code == 0) {
            this.setData({ 
              content: res.data.data.content,
              title: res.data.data.title
            });
          }
        }
      })
    },

});